package com.blog.service.Impl;
import com.blog.bean.domain.DiscussPost;
import com.blog.bean.domain.User;
import com.blog.mapper.Search.DiscussPostRepoistory;
import com.blog.mapper.UserMapper;
import com.blog.service.LikeService;
import com.blog.service.SearchService;
import com.blog.bean.vo.LikeVO;
import com.blog.bean.vo.PageAndUserVO;
import com.blog.bean.vo.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 任浩
 * @version 1.0
 */

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private LikeService likeService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DiscussPostRepoistory discussPostRepoistory;

    /**
     * 对文档内容的搜索。
     * @param content
     * @param page
     * @param pageNum
     * @param userId
     * @return
     */
    @Override
    public PageAndUserVO search(String content, Integer page, Integer pageNum, Integer userId) throws IOException {
        //使用es实现对文档内容的查询。
        //建立一个文档查找的请求。
        //建立一个文档查找的请求。

        System.out.println("搜索的数据为"+ content);

        SearchRequest searchRequest = new SearchRequest();
        //设置查找的索引
        searchRequest.indices("discusspost");

        //构建查询的请求题，就是构建查询的条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构建一个条件查询，根据内容来进行查询。
        searchSourceBuilder.query(QueryBuilders.termQuery("title",content));
        //进行排序
        searchSourceBuilder.sort("type", SortOrder.ASC);
        searchSourceBuilder.sort("status",SortOrder.ASC);
        searchSourceBuilder.sort("createTime",SortOrder.DESC);
        //进行分页查询。
        searchSourceBuilder.from(page-1);  //这是查询的页数
        searchSourceBuilder.size(pageNum); //这是查询的页面的大小
        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        System.out.println(hits.getTotalHits());
        log.info("hello");

        List<PageVO> list = new ArrayList<>();

        for (SearchHit hit : hits) {
            PageVO pageVO = new PageVO();
            DiscussPost discussPost = new DiscussPost();
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            discussPost.setId((Integer) sourceAsMap.get("id"));
            discussPost.setUserId((String) sourceAsMap.get("userId"));
            discussPost.setTitle((String) sourceAsMap.get("title"));
            discussPost.setContent((String) sourceAsMap.get("content"));
            discussPost.setType((Integer)sourceAsMap.get("type"));
            discussPost.setStatus((Integer) sourceAsMap.get("status"));
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate createTime = LocalDate.parse((String) sourceAsMap.get("createTime"), df);
            LocalDateTime localDateTime = createTime.atStartOfDay();
            discussPost.setCreateTime(localDateTime);
            discussPost.setCommentCount((Integer) sourceAsMap.get("commentCount"));
            discussPost.setScore((Double) sourceAsMap.get("score"));

            BeanUtils.copyProperties(discussPost,pageVO);

            //通过当前的用户id，查找发布帖子的用户信息。
            User user = new User();
            user.setId(Integer.parseInt(pageVO.getUserId()));
            user = userMapper.check(user);
            BeanUtils.copyProperties(user,pageVO);
            //重新赋值帖子id的值，因为用户id的值把帖子id的值给覆盖了。
            pageVO.setId((Integer) sourceAsMap.get("id"));

            //根据帖子的id，查询帖子的点赞信息。
            LikeVO likeVO = likeService.queryLike(pageVO.getId(),userId);
            pageVO.setLikeVO(likeVO);

            list.add(pageVO);
        }

        PageAndUserVO pageAndUserVO = new PageAndUserVO();
        pageAndUserVO.setCurPage(page);
        pageAndUserVO.setTotal(hits.getTotalHits().value);
        pageAndUserVO.setData(list);

        return pageAndUserVO ;
    }
}
